package com.tianji.learning.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tianji.api.client.course.CatalogueClient;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.IdAndNumDTO;
import com.tianji.api.dto.course.CataSimpleInfoDTO;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.course.CourseSimpleInfoDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.domain.query.PageQuery;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.*;
import com.tianji.learning.domain.LearningLesson;
import com.tianji.learning.domain.LearningRecord;
import com.tianji.learning.domain.dto.LearningPlanDTO;
import com.tianji.learning.domain.vo.LearningLessonVO;
import com.tianji.learning.domain.vo.LearningPlanPageVO;
import com.tianji.learning.domain.vo.LearningPlanVO;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.enums.PlanStatus;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.service.LearningLessonService;
import com.tianji.learning.mapper.LearningLessonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 阿娇的秘密星球
* @description 针对表【learning_lesson(学生课程表)】的数据库操作Service实现
* @createDate 2024-12-07 15:28:16
*/
@Service
public class LearningLessonServiceImpl extends ServiceImpl<LearningLessonMapper, LearningLesson>
    implements LearningLessonService{

    @Autowired
    private LearningLessonMapper learningLessonMapper;

    @Override
    public PageDTO<LearningLessonVO> getPage(PageQuery pageQuery) {
        Long user = UserContext.getUser();
        PageHelper.startPage(pageQuery.getPageNo(), pageQuery.getPageSize());
        Page<LearningLessonVO> p=learningLessonMapper.getPage(pageQuery,user);
        PageDTO<LearningLessonVO> objectPageDTO = new PageDTO<>();
        objectPageDTO.setList(p.getResult());
        objectPageDTO.setTotal(p.getTotal());
        objectPageDTO.setPages((long) p.getPages());
        return objectPageDTO;
    }

    @Autowired
    private CourseClient courseClient;

    @Autowired
    private CatalogueClient catalogueClient;
    @Override
    public LearningLessonVO getMyLesson() {
        Long userId = UserContext.getUser();
        if(ObjectUtils.isNull(userId)){
            throw new BadRequestException("非法用户");
        }
/*        List<LearningLesson> learningLessonList = this.lambdaQuery().eq(LearningLesson::getUserId, userId).list();
        List<LearningLessonVO> learningLessonVOList = BeanUtils.copyList(learningLessonList, LearningLessonVO.class);*/
        LambdaQueryWrapper<LearningLesson> queryWrapper = Wrappers.<LearningLesson>lambdaQuery().eq(LearningLesson::getUserId, userId)
                .eq(LearningLesson::getStatus, 1)
                .orderByDesc(LearningLesson::getLatestLearnTime)
                .last("limit 1");
        LearningLesson learningLesson = this.getOne(queryWrapper);
        LearningLessonVO learningLessonVO = BeanUtils.copyBean(learningLesson, LearningLessonVO.class);

        Integer count = this.lambdaQuery().eq(LearningLesson::getCourseId, learningLessonVO.getCourseId()).count();
        learningLessonVO.setCourseAmount(count);
        CourseFullInfoDTO courseInfoById = courseClient.getCourseInfoById(learningLessonVO.getCourseId(), false, false);

        learningLessonVO.setCourseCoverUrl(courseInfoById.getCoverUrl());
        learningLessonVO.setSections(courseInfoById.getSectionNum());
        learningLessonVO.setCourseName(courseInfoById.getName());


        List<CataSimpleInfoDTO> cataSimpleInfoDTOS = catalogueClient.batchQueryCatalogue(Arrays.asList(learningLesson.getLatestSectionId()));
        if(cataSimpleInfoDTOS!=null){
            CataSimpleInfoDTO cataSimpleInfoDTO = cataSimpleInfoDTOS.get(0);
            learningLessonVO.setLatestSectionName(cataSimpleInfoDTO.getName());
            learningLessonVO.setLatestSectionIndex(cataSimpleInfoDTO.getCIndex());
        }


        return learningLessonVO;
    }

    @Override
    public LearningLessonVO getCourseById(Long courseId) {
        LearningLesson learningLesson = this.lambdaQuery().eq(LearningLesson::getUserId, UserContext.getUser())
                .eq(LearningLesson::getCourseId, courseId).one();
        LearningLessonVO learningLessonVO = BeanUtils.copyBean(learningLesson, LearningLessonVO.class);
        return learningLessonVO;
    }

    @Override
    public void plans(LearningPlanDTO learningPlanDTO) {
        boolean b = this.lambdaUpdate().eq(LearningLesson::getCourseId, learningPlanDTO.getCourseId())
                .set(LearningLesson::getWeekFreq, learningPlanDTO.getFreq())
                .set(LearningLesson::getPlanStatus, PlanStatus.PLAN_RUNNING.getValue())
                .update();
        if(!b){
            throw new DbException("更新");
        }
    }

    @Autowired
    private LearningRecordMapper recordMapper;

    @Override
    public LearningPlanPageVO queryMyPlans(PageQuery query) {
       return null;
    }


    private Map<Long, CourseSimpleInfoDTO> queryCourseSimpleInfoList(List<LearningLesson> records) {
        // 3.1.获取课程id
        Set<Long> cIds = records.stream().map(LearningLesson::getCourseId).collect(Collectors.toSet());
        // 3.2.查询课程信息
        List<CourseSimpleInfoDTO> cInfoList = courseClient.getSimpleInfoList(cIds);
        if (CollUtils.isEmpty(cInfoList)) {
            // 课程不存在，无法添加
            throw new BadRequestException("课程信息不存在！");
        }
        // 3.3.把课程集合处理成Map，key是courseId，值是course本身
        Map<Long, CourseSimpleInfoDTO> cMap = cInfoList.stream()
                .collect(Collectors.toMap(CourseSimpleInfoDTO::getId, c -> c));
        return cMap;
    }
}




